import json
import logging
import os

from django.utils.deprecation import MiddlewareMixin

log = logging.getLogger(__name__)


class LogMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        # 响应返回给浏览器前被调用
        # 返回值只有响应对象
        data = None
        log.info(f"当前进程:{os.getpid()}")
        try:
            data = json.dumps(request.POST, ensure_ascii=False)
        except Exception:
            pass
        log.info(f"request:{request.method}-{request.path_info}-{request.META['QUERY_STRING']}-{data}")
        res_data = None
        try:
            res_data = json.dumps(response.data, ensure_ascii=False)
        except Exception:
            pass
        log.info(f"response: {response.status_code}-{res_data}")
        return response
